<template>
  <div class='container'>
    <el-dialog
    :title="`${data.id?'修改':'新增'}目录`"
    :visible.sync="dialogVisible"
    width="80%"
  >
    <span>
      <el-form ref="form" :model="newform" :rules="rules" label-width="100px">
          <el-form-item label="所属学科" v-if="!$route.query.id" prop="subjectID">
          <el-select v-model="newform.subjectID" style="width:100%">
            <el-option
              v-for="item in subjectOptions"
              :value="item.value"
              :label="item.label"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <br>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="newform.directoryName" />
        </el-form-item>
      </el-form>
      </span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible=false">取消</el-button>
        <el-button @click="confirm()" type="primary">确认</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys.js'
import { simple as subjectList } from '@/api/hmmm/subjects'
export default {
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      dialogVisible: false,
      subjectOptions: [],
      newform: {
        id: null,
        subjectID: null,
        directoryName: null,
        isFrontDisplay: 1
      },
      rules: {
        subjectID: [
          { type: 'number', message: '请选择所属学科', tirgger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入学科名称', tirgger: 'blur' }
        ]
      }
    }
  },
  async created () {
    // 学科下拉选项
    const { data: subjectArr } = await subjectList()
    this.subjectOptions = subjectArr
  },
  methods: {
    open () {
      this.dialogVisible = true
      if (this.data.id) {
        const { id, directoryName, isFrontDisplay } = this.data
        this.newform = { id, directoryName, isFrontDisplay }
      } else {
        this.newform = {
          id: null,
          directoryName: null,
          isFrontDisplay: 1
        }
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async confirm () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (!this.data.id) {
            await add(this.newform)
          } else {
            this.newform.id = this.data.id
            await update(this.newform)
          }
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
